<!-- 洗车页面 -->
<template>
  <!-- 页面 顶部轮播图部分 -->
  <swiper class="swiper" :circular="true" :autoplay="true" :interval="3000">
    <swiper-item
      class="swiper-item"
      v-for="(item, index) in swiperData"
      :key="item.id">
      <image :src="item.img" mode="widthFix" />
      <!-- 指示器 显示效果 1/5 -->
      <view class="swiper-indicator">
        {{ index + 1 }}/{{ swiperData.length }}
      </view>
    </swiper-item>
  </swiper>

  <!-- 页面 洗车店信息 -->
  <view class="merchant-info">
    <view class="merchant-info-title">小美洗车店</view>
    <view class="merchant-info-content">
      <!-- 左边星级 评分-->
      <view class="merchant-info-left">
        <view class="star">
          <view class="white-star">
            <view class="orange-star" :style="{ width: '80%' }"></view>
          </view>
        </view>
        <view class="evaluation">4.5分</view>
      </view>
      <!--右边 销量-->
      <view class="sales">销量：1000</view>
    </view>
    <view class="work-time">工作时间：9:00-21:00</view>
    <view class="address">地址：北京市朝阳区</view>
  </view>

  <!-- 页面 服务选择 部分 -->
  <view class="service-box">
    <checkbox-group @change="checkboxChange">
      <view class="box" v-for="item in serviceItems" :key="item.id">
        <label class="label-box">
          <view>
            <checkbox :value="item.id" :checked="item.checked" />
          </view>
          <view>{{ item.name }}</view>
        </label>
        <!-- 第二行 价格部分 -->
        <view class="price">
          <view class="present-price">￥{{ item.presentPrice }}</view>
          <view class="original-price">￥{{ item.originalPrice }}</view>
        </view>
        <!-- 第三行 服务介绍 -->
        <view class="introduction">{{ item.introduction }}</view>
      </view>
    </checkbox-group>
  </view>

  <!-- 页面 底部 用户评价部分 -->
  <view class="evaluation">
    <view class="evaluation-title">服务评价</view>
    <scroll-view
      scroll-y
      enable-flex
      class="scroll-view"
      @scrolltolower="loadMore"
      lower-threshold="60">
      <view class="scroll-item" v-for="item in evaluationData" :key="item.id">
        <!-- 左侧用户头像 -->
        <view class="user-avatar">
          <image :src="item.imgs" mode="aspectFill" />
        </view>
        <!-- 右侧信息评价部分 -->
        <view class="user-info">
          <!-- 用户名称 & 发表日期 -->
          <view class="one">
            <view>{{ item.name }}</view>
            <view>{{ item.time }}</view>
          </view>
          <!-- 星级 & 评分-->
          <view class="user-evaluation">
            <view class="star">
              <view class="white-star">
                <view
                  class="orange-star"
                  :style="{ width: item.rate * 20 + '%' }"></view>
              </view>
            </view>
            <view class="evaluation">{{ item.rate }}分</view>
          </view>
          <!-- 评价内容 -->
          <view class="evaluation-content">{{ item.content }}</view>
          <!-- 评价图片 -->
          <view class="evaluation-img">
            <image :src="item.imgs" mode="aspectFill" />
          </view>
        </view>
      </view>
      <!-- 底部加载 -->
      <view class="loading">
        {{ finish ? "没有更多了~" : "加载更多..." }}
      </view>
    </scroll-view>
  </view>
  <!-- 联系客服组件 -->
  <ContactService :phone="phone" />
  <!-- 公共订单组件 -->
  <CommonOrder @order="handleOrder">立即下单</CommonOrder>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useMerchantStore } from "@/stores/merchantInfo";
import {
  getServiceDetailsByMidApi,
  getEvaluationDataApi,
} from "@/api/WashCarApi";
import ContactService from "@/components/ContactService.vue";
import CommonOrder from "@/components/CommonOrder.vue";
import { useCheckedServiceStore } from "@/stores/CheckedService";
//定义pinia实例
const checkedServiceStore = useCheckedServiceStore();
//商户id
const merchantId = ref<number | null>(null);
//导入useMerchantStore 用来获取持久化的数据
const merchantStore = useMerchantStore();
//轮播图数据
const swiperData = ref<swiperItem[]>([]);
//定义单个商户的信息
const merchantInfo = ref<MerchantListResponse | undefined>(undefined);
//定义服务数组 包含服务的介绍 服务名字 服务原价格 打折后价格
const serviceItems = ref<ServiceItem[]>([
  {
    id: 1,
    name: "洗车",
    originalPrice: 20,
    presentPrice: 15,
    introduction: "深度清洗，焕然一新",
    mid: 1,
    checked: false,
  },
  {
    id: 2,
    name: "打蜡",
    originalPrice: 10,
    presentPrice: 8,
    introduction: "车内打蜡， shine like a new car",
    mid: 1,
    checked: false,
  },
]);
//定义 用户选中的服务内容
const checkedService = ref<ServiceItem[]>([]);
//测试 用户头像数据
const imgUrl = ref<string>(
  "https://lf-flow-web-cdn.doubao.com/obj/flow-doubao/doubao/chat/static/image/logo-icon-white-bg.72df0b1a.png"
);
//定义评价数据
const evaluationData = ref<EvaluationItem[]>([
  {
    id: 1,
    merchantId: 1,
    name: "用户1",
    orderId: 1,
    rate: 4.5,
    imgs: imgUrl,
    content: "这是用户对商户的评价内容。",
    time: "2025-06-01",
  },
  {
    id: 2,
    merchantId: 1,
    name: "用户2",
    orderId: 1,
    rate: 4.5,
    imgs: imgUrl,
    content: "这是用户对商户的评价内容。",
    time: "2025-06-01",
  },
  {
    id: 3,
    merchantId: 1,
    name: "用户3",
    orderId: 1,
    rate: 4.5,
    imgs: imgUrl,
    content: "这是用户对商户的评价内容。",
    time: "2025-06-01",
  },
  {
    id: 4,
    name: "用户4",
    merchantId: 1,
    orderId: 1,
    rate: 4.5,
    imgs: imgUrl,
    content: "这是用户对商户的评价内容。",
    time: "2025-06-01",
  },
  {
    id: 5,
    name: "用户5",
    merchantId: 1,
    orderId: 1,
    rate: 4.5,
    imgs: imgUrl,
    content: "这是用户对商户的评价内容。",
    time: "2025-06-01",
  },
]);
//定义评价部分 分页查询请求头参数
const evaluationRequestParams = ref<EvaluationRequestParams>({
  pageNum: 1,
  pageSize: 3,
  mid: 2,
});
//定义评价部分当前页
const currentPage = ref<number>(1);
//定义评价部分总页数
const totalPages = ref<number>(0);
//定义是否是最后一页
const finish = ref<boolean>(false);
//TODO定义手机号 用来获取登录用户的手机号
const phone = ref<string>("13811111111");

//函数 向轮播图数组添加id属性
const generate = (imgs: string[]) => {
  if (imgs.length && imgs.length > 0) {
    swiperData.value = imgs.map((item, index) => {
      return {
        id: index,
        img: item,
      };
    });
  }
};

//函数服务部分，根据商户id 查询该商户提供的服务
async function getServiceDetailsByMid(mid: number) {
  const res = await getServiceDetailsByMidApi(mid);
  console.log("商户提供的服务数据: ", res);
  if (res.code === 200) {
    serviceItems.value = res.data;
    //遍历数据 添加 checked属性
    serviceItems.value.forEach((item) => {
      item.checked = false;
    });
  }
}

//函数服务部分 复选框选中函数,选中的话需要看看用户是否提交订单
const checkboxChange = (event: any) => {
  console.log("复选框选中数据:", event.detail.value);
  //遍历serviceItems数组，修改选中的checked属性
  serviceItems.value.forEach((item) => {
    if (event.detail.value.includes(item.id.toString())) {
      item.checked = true;
    } else {
      item.checked = false;
    }
  });
  console.log("用户选中的内容:", JSON.stringify(serviceItems.value, null, 2));
};

//函数服务部分 立即下单事件
const handleOrder = () => {
  console.log("立即下单事件触发了...");
  //1. 筛选出用户选中的服务
  checkedService.value = serviceItems.value.filter((item) => item.checked);
  //2. 判断用户是否选中了服务
  if (checkedService.value.length === 0) {
    uni.showToast({
      title: "请选择服务",
      icon: "none",
      duration: 1500,
    });
    return;
  }

  //3. 将选中的数据持久化到pinia当中
  //使用pinia实例 调用方法
  checkedServiceStore.setCheckedServiceItemsList(checkedService.value);

  //4. 跳转页面到确认订单页面
  uni.navigateTo({
    url: "/pages/AffirmOrder/index",
  });
};

//函数用户评价部分，根据商户id，分页查询用户的评价数据
async function getEvaluationDataByMid(requestParams: EvaluationRequestParams) {
  const res = await getEvaluationDataApi(requestParams);
  console.log("评价数据: ", res);
  if (res.code === 200) {
    evaluationData.value = [...evaluationData.value, ...res.data.list];
    currentPage.value = res.data.pageNum;
    totalPages.value = res.data.pages;
    //判断是否是最后一页
    if (totalPages.value > 0 && currentPage.value === totalPages.value) {
      finish.value = true;
    }
  }
}

//函数用户评价部分，触底加载更多
const loadMore = () => {
  //加载更多之前判断是否是最后一页
  if (finish.value) {
    uni.showToast({
      title: "没有更多数据了",
      icon: "none",
      duration: 1500,
    });
    return;
  }

  //加载更多数据
  //修改请求参数中当前页的值
  evaluationRequestParams.value.pageNum = currentPage.value + 1;
  getEvaluationDataByMid(evaluationRequestParams.value);
};

//页面加载时获取传递过来的id
onLoad((options: any) => {
  console.log("传递过来的id是：", options.id);
  // 将字符串id转换为数字类型
  merchantId.value = Number(options.id);
  console.log("merchantId.value: onLoad " + merchantId.value);

  //api查询1: 根据商户id 获取商户的信息
  if (merchantId.value !== null) {
    merchantInfo.value = merchantStore.getMerchantInfoById(merchantId.value);
  }
  console.log("获取到的merchantId用户信息是：", merchantInfo.value);
  //获取轮播图数据
  generate(merchantInfo.value?.imgs || []);

  //api查询2: 根据商户id 获取商户提供的服务
  getServiceDetailsByMid(merchantId.value);

  //api查询3: 根据商户id 分页查询商户提供的服务
  //修改请求参数中商户id的值
  evaluationRequestParams.value.mid = merchantId.value;
  getEvaluationDataByMid(evaluationRequestParams.value);
});
</script>

<style scoped lang="scss">
/**样式 顶部轮播图的 */
.swiper {
  width: 100%;
  height: 350rpx;
  background-color: palegoldenrod;

  .swiper-item {
    width: 100%;
    height: 100%;
    position: relative;

    image {
      width: 100%;
      height: 100%;
    }

    .swiper-indicator {
      position: absolute;
      bottom: 10rpx;
      right: 25rpx;
      width: 120rpx;
      height: 50rpx;
      z-index: 10;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 25rpx;
      color: #fff;
      font-size: 36rpx;
    }
  }
}

/**样式 洗车商户信息 */
.merchant-info {
  box-sizing: border-box;
  padding: 20rpx 20rpx 35rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  background-color: #f0f0f0;

  .merchant-info-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #000;
  }

  .merchant-info-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20rpx;

    /**左边图片部分 */
    .merchant-info-left {
      display: flex;
      align-items: center;
      gap: 15rpx;
      /**左边星级部分 */
      .star {
        width: 118rpx;
        height: 25rpx;
        .white-star {
          width: 100%;
          height: 100%;
          background-image: url("https://bucket-yueyang.oss-cn-shanghai.aliyuncs.com/star-white.png");
        }
        .orange-star {
          width: 0;
          height: 100%;
          background-image: url("https://bucket-yueyang.oss-cn-shanghai.aliyuncs.com/star-orange.png");
        }
      }
    }

    /**右边销售部分 */
    .sales {
      flex: 1;
      margin-left: 35rpx;
    }
  }

  /**营业时间样式 */
  .work-time {
    font-size: 38rpx;
    color: #000;
  }
}

/**样式 中间服务部分 */
.service-box {
  margin: 20rpx 0;
  background-color: #f0f0f0;
}
.box {
  box-sizing: border-box;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  border: 1rpx solid #222436;
  border-radius: 10rpx;
  margin-bottom: 10rpx;

  .label-box {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 15rpx;
  }

  .price {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 30rpx;

    .present-price {
      font-size: 36rpx;
      color: #000;
      font-weight: bold;
    }
    .original-price {
      font-size: 28rpx;
      color: red;
      text-decoration: line-through;
    }
  }
}

/**样式 底部用户评价部分 */
.evaluation {
  box-sizing: border-box;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  /**用户评价标题 */
  .evaluation-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #000;
    margin-bottom: 20rpx;
  }
  /**scroll滑块 用户评价部分 */
  .scroll-view {
    height: 800rpx;
    width: 100%;
    padding-bottom: env(safe-area-inset-bottom);
    padding-bottom: constant(safe-area-inset-bottom);

    /**用户评价 */
    .scroll-item {
      display: flex;
      flex-direction: row;
      gap: 20rpx;
      border-radius: 20rpx;
      border-top-right-radius: 0;
      border-top-left-radius: 0;
      border-top: 2rpx solid #000;
      margin-bottom: 30rpx;
      /**评价用户头像部分 */
      .user-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        overflow: hidden;
        margin-top: 30rpx;
        image {
          width: 100%;
          height: 100%;
        }
      }
      /**评价部分样式 */
      .user-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        gap: 10rpx;
        .one {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 10rpx;
        }
        .user-evaluation {
          display: flex;
          align-items: center;
          .star {
            width: 118rpx;
            height: 25rpx;
            .white-star {
              width: 100%;
              height: 100%;
              background-image: url("https://bucket-yueyang.oss-cn-shanghai.aliyuncs.com/star-white.png");
            }
            .orange-star {
              width: 0;
              height: 100%;
              background-image: url("https://bucket-yueyang.oss-cn-shanghai.aliyuncs.com/star-orange.png");
            }
          }
          .evaluation {
            color: #000;
          }
        }
        .evaluation-content {
          font-size: 28rpx;
          color: #000;
        }
        .evaluation-img {
          width: 150rpx;
          height: 150rpx;
          image {
            width: 100%;
            height: 100%;
          }
        }
      }
    }

    /**底部加载更多样式 */
    .loading {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10rpx;
      box-sizing: border-box;
      margin-top: 20rpx;
    }
  }
}
</style>
